import axios from 'axios'
import qs from 'qs'

let baseURL = '';
if (process.env.NODE_ENV === 'development') {
    if(process.env.VUE_APP_BUILD==='devtest') {
        //本地测试接口
        baseURL = 'http://39.105.17.185';
    } else {
        //本地接口
        baseURL = 'http://39.105.17.185';
        baseURL = 'http://39.105.17.185';
    }
} else {
    if(process.env.VUE_APP_BUILD==='testing') {
        //线上测试
        baseURL = 'http://39.105.17.185';
    } else {
        //线上生产
        baseURL = 'http://39.105.17.185';
    }
}
const _axios = axios.create({
    baseURL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }
});

_axios.interceptors.request.use(config => {
    //token处理
    let LXbaseInfo = window.JSON.parse(window.localStorage.getItem('LXbaseInfo'));
    if (LXbaseInfo && LXbaseInfo.token) {
        config.headers.token = LXbaseInfo.token;
    }
    config.headers.authtoken = '47CF92AF12FB0';
    return config;
}, error => {
    return Promise.reject(error);
});


_axios.interceptors.response.use(response => {
    if (response && response.status === 200) {
        //正常情况
        if (response.data && response.data.code === 0) {
            return response.data;
        } else { //其他情况
            return Promise.reject(response.data);
        }
    } else {
        return Promise.reject(response.data);
    }
}, error => {
    let errorText = '';
    if (error && error.response) {
        switch (error.response.status) {
            case 401:
                errorText = '未授权，无法获取资源';
                break;
            case 403:
                errorText = '服务器拒绝访问';
                break;
            case 404:
                errorText = '请求错误，未找到资源';
                break;
            case 408:
                errorText = '请求超时';
                break;
            case 500:
                errorText = '服务器端出错';
                break;
            case 503:
                errorText = '服务器不可用';
                break;
            case 504:
                errorText = '网关超时';
                break;
            default:
                errorText = `请求错误${error.response.status}`
        }
        return Promise.reject({rtnInfo:errorText});
    } else {
        return Promise.reject({rtnInfo:'请求错误，请稍后重试'});
    }
});


class HttpRequest {
    static get(url, params = {}) {
        return _axios.get(url, params);
    }

    static post(url, params = {}) {
        return _axios.post(url, qs.stringify(params));
    }

    static delete(url, params = {}) {
        return _axios.delete(url, params);
    }


    static put(url, params = {}) {
        return _axios.put(url, params);
    }
}

export default HttpRequest;